package whf.framework.exception.handlers;

import java.util.List;
import java.util.Map;

import whf.framework.exception.UpdateException;
import whf.framework.service.SpringService;
import whf.framework.util.BeanFactory;
import whf.framework.util.TypeUtils;
import whf.framework.util.Utils;

/**
 * 异常链处理
 * @author wanghaifeng
 * @create Oct 19, 2006 3:04:11 PM
 * 
 */
public class ExceptionChainHandle extends SpringService implements IExceptionChainHandle{
	private static Map<Class, List<ExceptionHandler>> cache = Utils.newHashMap();
	
	private Map<String, List<ExceptionHandler>> configurations = Utils.newHashMap();
	
	public void setConfigurations(Map<String, List<ExceptionHandler>> configurations){
		this.configurations = configurations;
	}
	
	public static IExceptionChainHandle getExceptionChainHandle(){
		return (IExceptionChainHandle)BeanFactory.getBean("framework.ExceptionChainHandler");
	}
	
	/* (non-Javadoc)
	 * @see whf.framework.exception.handlers.IExceptionChainHandle#handle(java.lang.Throwable, java.util.Map)
	 */
	public void handle(Throwable t, Map parameters) throws ExceptionHandleEndException{
		List<ExceptionHandler> handlers = cache.get(t.getClass());
		if(handlers == null){
			handlers = Utils.newArrayList();
			List<Class> classes = TypeUtils.getSuperClasses(t.getClass());
			classes.add(t.getClass());
			for(Class c : classes){
				List<ExceptionHandler> hs = this.configurations.get(c.getName());
				if(hs == null) continue;
				for(ExceptionHandler h: hs){
					if(!handlers.contains(h)){
						handlers.add(h);
					}
				}
			}
			cache.put(t.getClass(), handlers);
		}
		for(ExceptionHandler handler: handlers){
			handler.handle(t, parameters);
		}
	}
	
	public static void main(String[] args) {
		System.out.println(TypeUtils.getSuperClasses(UpdateException.class));
	}
}
